<?php
/* 
 *to shipping orders--retail
 */
class ToShippingAction extends CommonAction {
    public function _filter(&$map) {
        //TODO
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
                $where['Sale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
                $where['Sale.customer_name'] = array('like',"%".$key."%");//产品名称
                $where['Sale.shipping_name'] = array('like',"%".$key."%"); 
                $where['Sale.logino'] = array('like',"%".$key."%");
                $where['Sale.address'] = array('like',"%".$key."%");
                $where['Sale.mobile'] = array('like',"%".$key."%");
                $where['Sale.phone'] = array('like',"%".$key."%");
                $where['Sale.remark'] = array('like',"%".$key."%");
            
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        if(!empty($_REQUEST['order_no'])) {
            $key2 = trim($_REQUEST['order_no']);
            if(!empty($_REQUEST['keywords']) || ($_REQUEST['etype'] == 'detail') )
              $map['_string'] = '(Sale.sale_no like "%'.$key2.'%")  OR ( Sale.mall_no like "%'.$key2.'%") ';
            else
              $map['_string'] = '(sale_no like "%'.$key2.'%")  OR ( mall_no like "%'.$key2.'%") ';
        }

        
        if( $_REQUEST['logicompany_id'] != '' )
          $map['logicompany_id'] = $_REQUEST['logicompany_id'];
        if($_REQUEST['logicompany_id'] == -1 )
          $map['logicompany_id'] = 0;
        if($_REQUEST['except_logicompany_id'] != "" )
          $map['logicompany_id'] = array('neq',$_REQUEST['except_logicompany_id']);

        if( $_REQUEST['order_source_id'] != '' )
          $map['order_source_id'] = $_REQUEST['order_source_id'];
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //审核时间
                $map['check_time '] = $cond_time;
                break;
              case '2': //发货时间
                $map['shipping_time '] = $cond_time;
                break;
              case '3': //下单时间
                if (empty($_REQUEST['keywords'])) {
                    
                    if($_REQUEST['etype'] == 'detail' ){ //导出订单详情，需按saleView进行搜索
                      $map['Sale.create_time '] = $cond_time;
                    }else
                      $map['create_time '] = $cond_time;
                }else
                    $map['Sale.create_time '] = $cond_time;
                break;
              case '4': //支付时间
                $map['pay_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

        if( $_REQUEST['order_status'] != '' )
          $map['order_status'] = $_REQUEST['order_status'];
        else
            $map['order_status'] = 2; //to shipping
        
        if( $_REQUEST['status'] != '' )
          $map['status'] = $_REQUEST['status'];
        else
            $map['status'] = 1; //checked
        if($_SESSION['warehouse_id'] == 1 ) //仅大眼窝控制配货状态
            $map['prepare_status'] = 0; //货齐未打印

        if( $_REQUEST['warehouse_id'] == '' )
            $map['warehouse_id'] = 1; //默认同普仓库
        else
            $map['warehouse_id'] = $_REQUEST['warehouse_id'];
        if($_SESSION['warehouse_id'] != 1 ) //代售
            $map['warehouse_id'] = $_SESSION['warehouse_id'];

    }

    public function  index() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        $wares = $this->countAgentToShipping();
        $this->assign('wares',$wares);
        //exception order message
        $message = M('Message');
        $count_todo = $message->where('status = 0 and depart=2')->count('id');
        $this->assign('count_todo',$count_todo);

        if(empty($_REQUEST['keywords']) ){
          
          if(!empty($_GET)){
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
          }
          parent::index('Sale',800);
        }else{ //view视图展示
            $model = D ('SaleView');
            if (! empty ( $model )) {
                $this->_list(D('SaleView'), $map, $sortBy = 'create_time desc', $asc = false,true, 800);
            }
            //pass parameters to export_order function
            $parameters = str_replace(__URL__.'?', '', __SELF__);
            $this->assign('parameters' ,$parameters);
            $this->display ();
            return;
        }
    }

     public function export_order($value='')
    {
       //替换查询的函数，可以得map.再导出结果
      //file type: order,order_detail,both
      $export_type = $_REQUEST['etype'];
      $map = $this->_search ();
      if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
          $map['warehouse_id'] = $_SESSION['warehouse_id'];
      switch ($_REQUEST['action']) {
        case 'prepare':
          A('Prepare')->_filter($map);
          break;
        case 'shipped':
          A('Shipped')->_filter($map);
          break;
        case 'outstock':
          A('OutStock')->_filter($map);
          break;

        default: //toshipping
          $this->_filter ( $map );
          break;
      }
      $line = "";
      $data = array();
      $express = S('Express');
      $order_source = S('order_source');
      $goods = S('goods');
      $category = S('category');
      switch ($export_type) {
         case 'order':
             if(empty($_REQUEST['keywords']) && $_REQUEST['action'] != outstock  )
                    $voList = D('Sale')->where($map)->group('id')->findAll( );
              else
                $voList = D('SaleView')->where($map)->group('sale_id')->findAll( );
               $title ="订单号,原始单号,会员名,货款,运费,应付款,实付款,订单状态,买家留言,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,审核时间,发货时间,物流单号,物流公司,订单备注,宝贝总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => "'".$value['sale_no'],
                     'mall_no' => "'".$value['mall_no'],
                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['sale_no']),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                     'real_pay' => $value['sum_pay'], //暂用理论总金额 代替实付款
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      'customer_msg' => iconv('utf-8','GBK',$value['customer_msg'] ),
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      

                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),
                      'check_time' => toDate($value['check_time']),
                      'shipping_time' => toDate($value['shipping_time']),

                      'logino' => $value['logino'],
                      'logicompany' => iconv('utf-8','GBK',$express[$value['logicompany_id'] ]['name'] ), //中文转码 
                      
                      'remark' => iconv('utf-8','GBK',$value['remark']),
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK',$order_source[$value['order_source_id']] ),
                     );
                    $line .= build_csv_line($data);
                    unset($data);
                } 
                $filename = "DYW_order".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);
               break;
            case 'detail':
               if($_REQUEST['action'] == 'outstock' )
                    $voList = D('Sale_detailView')->where($map)->findAll( );
               else
                   $voList = D('SaleView')->where($map)->findAll( );
               $title ="订单号,会员名,商品名称,销售标题,所属产品,商品类别,单价,数量,小计,下单时间,审核时间,备注\n";
                $title = iconv('utf-8', 'GBK', $title);
                $data = array();
                
               $common_products = S('products');
            if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $common_id = $goods[$value['product_id']]['common_id'];
                  $data= array(
                     'sale_no' => "'".$value['sale_no'],
                     'customer_name' => iconv('utf-8', 'GBK',$value['customer_name'] ),
                     'pname' => iconv('utf-8', 'GBK',$goods[$value['product_id']]['name'] ),
                     'sale_title' => iconv('utf-8', 'GBK',$value['sale_title'] ),
                     'common_product' => iconv('utf-8', 'GBK',$common_products[$common_id]['name'] ), //所属产品
                     'cat_id' => iconv('utf-8', 'GBK',$category[$goods[$value['product_id']]['cat_id']]), //类别
                     'price' => $value['price'],
                     'number' => $value['number'],
                     'total' => $value['dtotal'],
                     'create_time' => toDate( $value['create_time'] ),
                     'check_time' => toDate( $value['check_time'] ),
                     'remark' => iconv('utf-8', 'GBK',$value['remark']),
                     );
                   $line .= build_csv_line($data);
                    unset($data);
                }
                $filename = "DYW_goods".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);

               break;
             case 'both':

             default:
               if(empty($_REQUEST['keywords']) && $_REQUEST['action'] != outstock )
                $voList = D('Sale')->where($map)->group('id')->findAll( );
              else{
                   $voList = D('SaleView')->where($map)->findAll( );
                }


               $title ="订单号,原单号,会员名,货款,运费,应付款,实付款,订单状态,买家留言,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,物流单号,物流公司,订单备注,宝贝总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' =>"'".$value['sale_no'],
                     'mall_no' => "'".$value['mall_no'],
                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['sale_no']),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                     'real_pay' => $value['sum_pay'], //暂用理论总金额 代替实付款
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      'customer_msg' => iconv('utf-8','GBK',$value['customer_msg'] ),
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      

                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),

                      'logino' => $value['logino'],
                      'logicompany' => iconv('utf-8','GBK',$express[$value['logicompany_id'] ]['name'] ), //中文转码 
                      
                      'remark' => iconv('utf-8','GBK',$value['remark']),
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK',$order_source[$value['order_source_id']] ),
                     );
                  $line .= build_csv_line($data);
                    unset($data);
                    $goods_detail = M('Sale_detail')->where('sale_no ="'.$value['sale_no'].'"')->findAll();
                    foreach ($goods_detail as  $v) {
                      $goods_data= array(
                       'blank' => "",
                       'sale_title' => iconv('utf-8', 'GBK',$v['sale_title'] ),
                       'pname' => iconv('utf-8', 'GBK',$goods[$v['product_id']]['name'] ),
                       
                       'product_id' => $v['product_id'],
                       'out_number' => $v['out_number'],
                       'price' => $v['price'],
                       'number' => $v['number'],
                       'total' => $v['total']
                     );
                      $line .= build_csv_line($goods_data);
                    }
                    
                }

                $filename = "DYW_OrderGoods".date('Ymd_His').'.csv'; //设置文件名 
                export_csv($filename,$title.$line);
               break;
           }     
    }


 //生成捡货单
    public function pick_goods($tpl="pick_goods"){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
          
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能捡货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];
            $list = M('Sale') ->where ( $condition )->field('id')->findAll();
            $sale_ids = array(); //有效的SALE_ID
            if(!is_array($list))
                $this->error('您选择的订单不存在！');
            foreach ($list as $key => $value) {
              $sale_ids[$key] = $value['id'];
            }
            $id = implode(',', $sale_ids  );
            $detailView = M('Sale_detail');
            //$sqlstr = "select sum(number) as number,product_id,cat_id,p.name as pname,is_virtual,sale_title,options from vm_sale_detail as sd left join vm_product as p on sd.product_id = p.id  where sd.sale_id in (".$id.") group by p.id order by p.cat_id,p.name,p.brand_id";
            $sqlstr = "select sum(number) as number,product_id,cat_id,p.name as pname,is_virtual,sale_title,options from vm_sale_detail as sd left join vm_product as p on sd.product_id = p.id  where sd.sale_id in (".$id.") group by p.id order by p.cat_id,p.name,p.brand_id";
            $goods_list = M('')->query($sqlstr);
            
            $this->assign('orders',$goods_list);
            $this->display($tpl);
        }else
          $this->error("请选择订单！");
    }

    //导出拣货单
    public function export_picklist()
    {
      $id = $_REQUEST['oid'];
        if (isset ( $id )) {
          
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能捡货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            $list = M('Sale') ->where ( $condition )->field('id')->findAll();
            $sale_ids = array(); //有效的SALE_ID
            if(!is_array($list))
                $this->error('您选择的订单不存在！');
            foreach ($list as $key => $value) {
              $sale_ids[$key] = $value['id'];
            }
            $map = array ('sale_id' => array ('in',  $sale_ids  ));

            $detailView = M('Sale_detail');
            $goods_list = $detailView -> where($map)->order('product_id,sale_title')->findAll();
            
            //合并同产品数量
            $temp = array();
            foreach ($goods_list as $k => $v) { 
              if( $v['product_id'] != 0 ){ //如果产品ID 不为0时，则合并数量
                  $kk = $v['product_id'];
                  if( isset($temp[$kk]['number']) ) //合并
                      $temp[$kk]['number'] = ($v['number'] + $temp[$kk]['number'] ); 
                  else {
                     $temp[$kk]['number'] =  $v['number'];
                     $temp[$kk] = $v;
                  }
              } else{
                  $temp[$k] = $v;
              }

            }
            
            $title ="商品,数量\n";
                $title = iconv('utf-8', 'GBK', $title);
                $line = "";
                $data = array();
                foreach ($temp as $value) {
                  $data= array(
                    'product_name' => empty($value['product_id']) ? iconv('utf-8', 'GBK', $value['sele_title']) :
                       iconv('utf-8', 'GBK', getModelName($value['product_id'] ,'Product' ) ) ,
                    'number' => $value['number'],
                    
                    );
                    $line .= build_csv_line($data);
                    unset($data);
              }
               $filename = "DYW_picklist".date('Ymd_His').'.csv'; //设置文件名 
                
              export_csv($filename,$title.$line);

        }else
          $this->error("请选择订单！");
    }

    //生成配货单
    public function invoice($tpl="invoice"){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能配货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //优先按收货人，地址排列，再按审核时间升序排列 ，便于正常合并订单
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
            if(!is_array($list))
                $this->error('您选择的订单不存在！');

            $new_orders = array();
            foreach ($list as $key => $value) {
              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            
            $this->assign('orders',$new_orders);
            $this->display($tpl);
        }else
          $this->error("请选择订单！");
    }

    //导出配货单
    public function export_invoice()
    { 
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能配货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //优先按收货人，地址排列，再按审核时间升序排列 ，便于正常合并订单
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
            if(!is_array($list))
                $this->error('您选择的订单不存在！');

            $new_orders = array();
            foreach ($list as $key => $value) {
              if(is_all_virtual($value['id']) == 1 )
                 continue; //如果全部是虚拟物品，则不处理

              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }

            $title ="订单编号,会员名,订购日期,收货人姓名,手机,联系电话,收货地址,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                $line = "";
                $data = array();
                foreach ($new_orders as $value) {
                  $data= array(
                    'sale_no' => $value['sale_no'],
                    'customer_name' => iconv('utf-8', 'GBK', $value['customer_name']),
                    'create_time' => toDate( $value['create_time'] ),
                    'shipping_name' => iconv('utf-8', 'GBK', $value['shipping_name'] ),
                    'mobile' => $value['mobile'],
                    'phone' => $value['phone'],
                    'address' => iconv('utf-8', 'GBK', $value['address'] ),
                    'order_source' => iconv('utf-8','GBK',getModelName( $value['order_source_id'] , 'Order_source') ),
                     
                    );
                    $line .= build_csv_line($data);
                    unset($data);

                    //get goods detail
                    $condition = array ('sale_id' => array ('in', explode ( ',', $value['id'] ) ) );
                    
                    $sale_details = M('Sale_detail')->where($condition)->order('product_id asc')->findAll(); 
                    $order_detail = array();
                    $order_detail = $this -> merge_order_detail($order_detail,$sale_details);

                    $goods_data = array();
                    foreach ($order_detail as  $v) {
                      $is_virtual = getModelName($v['product_id'],'Product','is_virtual'); 
                      if($is_virtual == 1 )
                        continue; //虚拟商品跳过处理
                      $goods_data= array(
                       'blank' => "",
                       'pname' => iconv('utf-8', 'GBK',getModelName( $v['product_id'] ,'Product') ),
                       
                       'price' => $v['price'],
                       'number' => $v['number'],
                       'total' => $v['total']
                     );
                      $line .= build_csv_line($goods_data);
                    }

                } 
                $filename = "DYW_invoice".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);

        }else
            $this->error("请选择订单！");
         
    }

     protected function merge_order(&$new_orders,$list,$value,$key){
      
        //如果地址及收货人相同，则合并订单,并且是同一平台下的
      //TODO 存在不同快递的情况，需要排除
          if( trim( $list[$key - 1]['shipping_name'] ) == trim($value['shipping_name'] ) 
              && trim( $list[$key - 1]['address'] )  == trim( $value['address'] )
              && ( $list[$key-1]['order_source_id'] == $value['order_source_id']  )
              && $list[$key-1]['logino'] == $value['logino']  //快递单号相同时才能合并
               ){

             if( is_array($new_orders[$key-1]) ){ //仅存在数组时，才合并
                $new_orders[$key - 1]['id'] .= ','.$value['id'];
                $new_orders[$key - 1]['sale_no'] .= ','.$value['sale_no'];
             }else{
                //不是数组，进入上一层数组,递归
                if($key-1 >0){
                   $this->merge_order($new_orders,$list,$value,$key-1);
                }
              } }else
          $new_orders[$key] = $value;

      return $new_orders;
  }

    //导出快递地址
    public function shipping(){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能配货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //按审核时间升序排列
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
            if(!is_array($list))
                $this->error('您选择的订单不存在！');

             $new_orders = array();
            foreach ($list as $key => $value) {
              if(is_all_virtual($value['id']) == 1 )
                 continue; //如果全部是虚拟物品，则不导出快递
              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            $goods = S('goods'); //缓存的货品数据
            $p_index = 1; //计数
            $str ="物品内容,快递,收货人,手机,电话,地址,省份,城市,区县,重量,订单摘要\n";
            $str = iconv('utf-8', 'GBK', $str);
            foreach ($new_orders as $value) {
                  $sale_detail_str = "";//订单内商品明细
                  //合并订单用in
                  $sale_detail = M('Sale_detail')->where('sale_id in ( '.$value['id'].')')->field('product_id,number')->findAll();
                  foreach($sale_detail as $sdetail ){
                      //TODO 部分虚拟商品未去除
                      $sale_detail_str .= "  ".iconv('utf-8','GBK',$goods[$sdetail['product_id']]['name'] ."  数量：".$sdetail['number'])."\n"; 
                  }

                  $name = iconv('utf-8','GBK',$value['shipping_name']); //中文转码 
                  $logicompany = iconv('utf-8','GBK',getModelName( $value['logicompany_id'],'Logicompany' ) ); //中文转码 
                  $address = iconv('utf-8','GBK',$value['address']); 
                  $mobile = iconv('utf-8','GBK',$value['mobile']);
                  $phone = iconv('utf-8','GBK',$value['phone']);
                  $province = iconv('utf-8','GBK',$value['province']);
                  $city = iconv('utf-8','GBK',$value['city']);
                  $county = iconv('utf-8','GBK',$value['county']);
                  $sale_no = iconv('utf-8','GBK',$value['sale_no']." 隐形眼镜 护理液");  
                 // if( strpos($sale_no, ',') !== false ) 下面已经处理，这里不再重复
                   //  $sale_no = "'".$sale_no;
                  $str .= '"\''.$sale_no.'",'.$logicompany.',"'.$name.'","'.$mobile.'","'.$phone.'","'.$address.'"'.','.$province.','.$city.','.$county.','.$p_index.',"'.$sale_detail_str.'"'."\n"; //用引文逗号分开 
                  $p_index ++;
            } 
            $filename = "DYW_shipping".date('Ymd_His').'.csv'; //设置文件名 
            export_csv($filename,$str); //导出 

        }else
          $this->error("请选择订单！");
    }

     //导出韵达专用快递excel
    public function yunda_shipping(){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能配货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //按审核时间升序排列
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
            if(!is_array($list))
                $this->error('您选择的订单不存在！');

             $new_orders = array();
            foreach ($list as $key => $value) {
              if(is_all_virtual($value['id']) == 1 )
                 continue; //如果全部是虚拟物品，则不导出快递
              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            //导出Excel
            import('@.ORG.PHPExcel.IOFactory','','.php');
            

            spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别
            $objPHPExcel=new PHPExcel();
            $objPHPExcel->getProperties()->setCreator('DYW ERP')
               ->setLastModifiedBy('DYW ERP')
               ->setTitle('韵达快递')
               ->setSubject('韵达快递')
               ->setDescription('韵达快递地址')
               ->setCategory('Result file');
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A1','订单号')
                        ->setCellValue('B1','发件人姓名')
                        ->setCellValue('C1','发件人手机')
                        ->setCellValue('D1','发件人详细地址')
                        ->setCellValue('E1','自定义区域1')
                        ->setCellValue('F1','收件人姓名')
                        ->setCellValue('G1','收件人手机')
                        ->setCellValue('H1','收件人详细地址')
                        ->setCellValue('I1','自定义区域2');

            $goods = S('goods'); //缓存的货品数据
            $p_index = 1; //计数
            
            $i=2; 
            foreach ($new_orders as $value) {
                  $from_name = "隐形眼镜上海仓";
                  $from_mobile = "021-62563719";
                  $from_address = "上海同普路";
                  $custom_area1 = "隐形眼镜";
                  $name = $value['shipping_name']; //中文转码 
                  $address = $value['address']; 
                  $mobile = empty($value['mobile']) ? $value['phone']:$value['mobile'];
                  $sale_no = $value['sale_no']; 
                  $objPHPExcel->setActiveSheetIndex(0)
                      ->setCellValueExplicit('A'.$i,$sale_no,PHPExcel_Cell_DataType::TYPE_STRING) //设置为文本格式
                      //->setCellValue('A'.$i,$sale_no)
                      ->setCellValue('B'.$i,$from_name)
                      ->setCellValue('C'.$i,$from_mobile)
                      ->setCellValue('D'.$i,$from_address)
                      ->setCellValue('E'.$i,$custom_area1)
                      ->setCellValue('F'.$i,$name)
                      ->setCellValue('G'.$i,$mobile)
                      ->setCellValue('H'.$i,$address)
                      ->setCellValue('I'.$i,$p_index);
                  $i++;
                  $p_index ++;
            } 
            $objPHPExcel->getActiveSheet()->setTitle('yunda');
            $objPHPExcel->setActiveSheetIndex(0);
            
            //生成xls文件
            $filename = "DYW_yunda".date('Ymd_His').'.xls'; //设置文件名 
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename);
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;

        }else
          $this->error("请选择订单！");
    }

     //导出圆通标准快递模板excel
    public function yt_shipping(){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //只有审核通过的订单才能配货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //按审核时间升序排列
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
            if(!is_array($list))
                $this->error('您选择的订单不存在！');

             $new_orders = array();
            foreach ($list as $key => $value) {
              if(is_all_virtual($value['id']) == 1 )
                 continue; //如果全部是虚拟物品，则不导出快递
              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            //导出Excel
            import('@.ORG.PHPExcel.IOFactory','','.php');
            

            spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别
            $objPHPExcel=new PHPExcel();
            $objPHPExcel->getProperties()->setCreator('DYW ERP')
               ->setLastModifiedBy('DYW ERP')
               ->setTitle('圆通快递标准模板')
               ->setSubject('圆通快递标准模板')
               ->setDescription('韵达快递地址')
               ->setCategory('Result file');
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A1','订单号')
                        ->setCellValue('B1','商品名称')
                        ->setCellValue('C1','数量')
                        ->setCellValue('D1','买家姓名')
                        ->setCellValue('E1','买家收货省')
                        ->setCellValue('F1','买家收货市')
                        ->setCellValue('G1','买家收货区')
                        ->setCellValue('H1','买家地址')
                        ->setCellValue('I1','买家手机号')
                        ->setCellValue('J1','发件人')
                        ->setCellValue('K1','发件人省')
                        ->setCellValue('L1','发件人市')
                        ->setCellValue('M1','发件人区')
                        ->setCellValue('N1','发件地址')
                        ->setCellValue('O1','发件人邮编')
                        ->setCellValue('P1','代收货款')
                        ->setCellValue('Q1','备注')
                        ->setCellValue('R1','买家邮编')
                        ->setCellValue('S1','买家电话');

            $goods = S('goods'); //缓存的货品数据
            $p_index = 1; //计数
            
            $i=2; 
            foreach ($new_orders as $value) {
                  $from_name = "隐形眼镜上海仓";
                  $from_mobile = "021-62563719";
                  $from_address = "上海同普路";
                  $custom_area1 = "隐形眼镜";
                  $name = $value['shipping_name']; //中文转码 
                  $address = $value['address']; 
                  //$mobile = empty($value['mobile']) ? $value['phone']:$value['mobile'];
                  $mobile = $value['mobile']; //先仅手机号
                  $sale_no =str_replace(',', 'A', $value['sale_no']); //替换掉逗号分隔的合并订单号为A结合 
                  $sale_no =str_replace('-', 'C', $sale_no); //替换掉-分隔的订单号为C结合 
                  $real_geo = getGEO($address);
                  $province = empty($value['province']) ? $real_geo[0] : $value['province'];
                  $city = empty($value['city']) ? $real_geo['1'] : $value['city'];
                  $county = empty($value['county']) ? $real_geo['2'] : $value['county'];
                  $county = empty($county) ? $city : $county;
                  $objPHPExcel->setActiveSheetIndex(0)
                      ->setCellValueExplicit('A'.$i,$sale_no,PHPExcel_Cell_DataType::TYPE_STRING) //设置为文本格式
                      //->setCellValue('A'.$i,$sale_no)
                      ->setCellValue('B'.$i,$custom_area1)
                      ->setCellValueExplicit('C'.$i,$value['sum_number'],PHPExcel_Cell_DataType::TYPE_NUMERIC) //数字格式)
                      ->setCellValue('D'.$i,$name)
                      ->setCellValue('E'.$i,$province)
                      ->setCellValue('F'.$i,$city)
                      ->setCellValue('G'.$i,$county)
                      ->setCellValue('H'.$i,$address)
                      ->setCellValue('I'.$i,$mobile)
                      ->setCellValueExplicit('I'.$i,$mobile,PHPExcel_Cell_DataType::TYPE_NUMERIC) //数字格式
                      ->setCellValue('J'.$i,$from_name)
                        ->setCellValue('K'.$i,'上海')
                        ->setCellValue('L'.$i,'上海市')
                        ->setCellValue('M'.$i,'普陀区')
                        ->setCellValue('N'.$i,$from_address."      ".$p_index) //在地址中加入打印序号
                        ->setCellValue('O'.$i,'200062')
                        ->setCellValue('P'.$i,'') //代收货款
                        ->setCellValue('Q'.$i,toDate(time())) //备注 加导入时间
                        ->setCellValue('R'.$i,'') //买家邮编
                        ->setCellValue('S'.$i,$value['phone']);
                  $i++;
                  $p_index ++;
            } 
            $objPHPExcel->getActiveSheet()->setTitle('yuantong');
            $objPHPExcel->setActiveSheetIndex(0);
            
            //生成xls文件
            $filename = "DYW_yt".date('Ymd_His').'.xls'; //设置文件名 
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename);
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;

        }else
          $this->error("请选择订单！");
    }

    //批量发货,界面显示全部的待发货的，但扫描时还是一个一个发的货
    public function doshipping($tpl="doshipping"){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //审核通过
            $condition['order_status'] = 2;  //只有待发货的订单才能使用批量发货功能

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //$condition['logino'] = ''; //可以重新发货，修正之前的错误运单号
            //按审核时间进行发货
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
           
            if(!is_array($list))
                $this->error('您选择的订单不存在或已经发货！');

            $new_orders = array();
            foreach ($list as $key => $value) {
              //if(is_all_virtual($value['id']) == 1 )
                // continue; //如果全部是虚拟物品，则不处理

              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            
            $this->assign('orders',$new_orders);
            $this->display($tpl);
        }else
          $this->error("请选择订单！");
    }

    public function create_logino($tpl="create_logino"){
      $start_no = $_REQUEST['start_no'];
      $end_no = $_REQUEST['end_no'];
      $this->check_logino($start_no,$_POST['logicompany_id']);
      $this->check_logino($end_no ,$_POST['logicompany_id'] );


      $count_orders = $_REQUEST['count_orders'];
      if( ($end_no - $start_no+1) !=  $count_orders )
        $this->error("输入的单号数量不等于发货单数量，请重新输入",false,5);

      $oid = $_REQUEST['oid'];
      if (isset ( $oid )) {
            $condition = array ('id' => array ('in', explode ( ',', $oid ) ) );
            $condition['status'] = 1; //审核通过
            $condition['order_status'] = 2;  //只有待发货的订单才能使用批量发货功能
            $condition['logino'] = '';

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            //按审核时间进行发货
            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
           
            if(!is_array($list))
                $this->error('您选择的订单不存在或已经发货！',false,10);

            $new_orders = array();
            foreach ($list as $key => $value) {
              if(is_all_virtual($value['id']) == 1 )
                 continue; //如果全部是虚拟物品，则不处理

              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            
            $this->assign('orders',$new_orders);
            $this->assign('count_orders',count($new_orders));
            $this->assign('oid',$id);
            $this->assign('start_no',$start_no);
            $this->assign('end_no',$end_no);
            $this->display($tpl);
        }else
          $this->error("请选择订单！");
    }

    //批量发货,仅显示默认的快递（如天天快递）的待发货列表，设置运单起步号及终止号可自动填写。
    public function mass_doshipping($tpl="mass_doshipping"){
        $id = $_REQUEST['oid'];
        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $condition['status'] = 1; //审核通过
            $condition['order_status'] = 2;  //只有待发货的订单才能使用批量发货功能
            $condition['logino'] = '';/*
            $condition['logicompany_id'] =  array(
              array('eq',0),
              array('eq',37),
              'or',
            );*/ //未指定快递的或默认是天天快递的
            //按审核时间进行发货

            if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
                $condition['warehouse_id'] = $_SESSION['warehouse_id'];

            $list=M('Sale')->where ( $condition )->order('shipping_name desc,address desc,check_time asc')->findAll();
           
            if(!is_array($list))
                $this->error('您选择的订单不存在或已经发货！');

            $new_orders = array();
            foreach ($list as $key => $value) {
              if($key > 0){
                //如果收货人及地址相同，则合并订单
                 $new_orders = $this->merge_order($new_orders,$list,$value,$key); 

              }else
                $new_orders[$key] = $value;
            }
            
            $this->assign('orders',$new_orders);
            $this->assign('count_orders',count($new_orders));
            $this->assign('oid',$id);
            $this->display($tpl);
        }else
          $this->error("请选择订单！");
    }

     //默认不填快递公司情况下，如果运单号小于12或不为数字，则提示错误；其他情况根据快递公司规则处理
   private function check_logino($logino,$logicompany_id = 0){
    //如果不为空时，则进行判断
    if(!empty($logino)){
        if( $logicompany_id == 20 && strlen($logino) != 12 && strlen($logino) != 10 )  //yuan通 12
          $this->error("圆通运单号位数必须等于 12或10位！",false,5);
        else if( $logicompany_id == 21 && strlen($logino) != 13 )  //韵达 13位
          $this->error("韵达运单号位数必须等于 13！",false,5);
        else if( $logicompany_id == 17 && strlen($logino) != 12 )  //中通 12
          $this->error("中通运单号位数必须等于 12！",false,5);
        else if( $logicompany_id == 18 && strlen($logino) != 12 )  //汇通快运 12
          $this->error("汇通快运 运单号位数必须等于 12！",false,5);
        else if( $logicompany_id == 27 && strlen($logino) != 13 )  //邮政国内小包 27
          $this->error("邮政国内小包运单号位数必须等于 13！",false,5);
        else if(!is_numeric($logino))
          $this->error('运单号只能为数字！'); //TODO 五环可能有问题，是字母加数字
      }
     

    }

  //必须按product_id排序，才能使用合并方法
  public function merge_order_detail(&$order_detail,$sale_detail){
        foreach ($sale_detail as $key => $value) {
            $this -> __merge_order_detail($order_detail,$sale_detail,$value,$key);
        } return $order_detail;
    }

  public  function __merge_order_detail(&$order_detail,$sale_detail,$value,$key){
       
            if($key == 0)
                $order_detail[0] = $value;
            else{
                if( $value['product_id'] != 0 && 
                  $value['product_id'] == $sale_detail[$key-1]['product_id']
                    ){
                    if(is_array($order_detail[$key-1])){
                       $order_detail[$key-1]['number'] += $value['number'];
                        $order_detail[$key-1]['total'] += $value['total']; 
                    }else{
                        $this->__merge_order_detail($order_detail,$sale_detail,$value,$key-1); }
                    }else
                   $order_detail[$key] = $value;
            }
        return $order_detail;
    }


public function update()
{
    A('Sale')->update();
}

public function edit()
{
    parent::edit('Sale');
}

//set those inovices to print
public function print_invoice(){
  $oid = $_POST['oid'];
  $condition = array ('id' => array ('in', explode ( ',', $oid ) ) );

  if($_SESSION['warehouse_id'] != 1 )//非大眼窝用户 ,则控制所属仓库
       $condition['warehouse_id'] = $_SESSION['warehouse_id'];

  $sid = M('Sale')->where($condition)->setField('prepare_status',1);

  $s_condition = array ('sale_id' => array ('in', explode ( ',', $oid ) ) );
  $sdid = M('Sale_detail')->where($s_condition)->setField('prepare_status',1);
  if($sid && $sdid)
      $data['is_print'] = 1;
  else
      $data['is_print'] = 0;
  $this->ajaxReturn($data,'',1);
}

  public function countAgentToShipping(){
      //get agent warehouse
      $wares = M('Warehouse')->where('id !=1 and status=1' )->field('id,name')->findAll();
      foreach( $wares as $wk=>$wv ){
          $wares[$wk]['count_toshipping'] = M('Sale')->where('warehouse_id = '.$wv['id']." and status=1 and order_status = 2")->count('id');      
      }
      return $wares;
  }

  private function export_excel($filename,$data) { 
        header('Content-Type: application/vnd.ms-excel');  
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        $fp = fopen('php://output', 'a'); 
    }

}
?>
